/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.tag.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.el.ELException;
import javax.el.VariableMapper;

import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.TagConfig;
import org.skatiger.jrove.TagHandler;
import org.skatiger.jrove.TemplateClient;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.el.VariableMapperWrapper;
import org.skatiger.jrove.tag.TagAttribute;
import org.skatiger.jrove.tag.TagAttributeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class DecorateHandler extends TagHandler
        implements TemplateClient {

    private static final Logger logger = LoggerFactory.getLogger(DecorateHandler.class);

    private final TagAttribute template;

    private final Map<String, DefineHandler> handlers;

    private final ParamHandler[] params;

    /**
     * @param config
     */
    public DecorateHandler(TagConfig config) {
        super(config);
        this.template = this.getRequiredAttribute("template");
        this.handlers = new HashMap<String, DefineHandler>();

        Iterator<DefineHandler> defines = this.findNextByType(DefineHandler.class);
        while (defines.hasNext()) {
            DefineHandler d = defines.next();
            this.handlers.put(d.getName(), d);
            logger.debug(tag + " found Define[" + d.getName() + "]");
        }
        List<ParamHandler> paramC = new ArrayList<ParamHandler>();
        Iterator<ParamHandler> paramsitr = this.findNextByType(ParamHandler.class);
        while (paramsitr.hasNext()) {
            paramC.add(paramsitr.next());
        }
        if (paramC.size() > 0) {
            this.params = paramC.toArray(new ParamHandler[paramC.size()]);
        } else {
            this.params = null;
        }
    }

    public void apply(JroveContext ctx, UIComponent parent) throws IOException, JroveException, ELException {
        VariableMapper orig = ctx.getVariableMapper();
        if (this.params != null) {
            VariableMapper vm = new VariableMapperWrapper(orig);
            ctx.setVariableMapper(vm);
            for (int i = 0; i < this.params.length; i++) {
                this.params[i].apply(ctx, parent);
            }
        }

        String path = null;
        ctx.pushClient(this);
        try {
            path = this.template.getValue(ctx);
            ctx.includeJrove(parent, path);
        } catch (IOException e) {
            throw new TagAttributeException(this.tag, this.template, "Invalid path : " + path);
        } finally {
            ctx.setVariableMapper(orig);
            ctx.popClient(this);
        }
    }

    public boolean apply(JroveContext ctx, UIComponent parent, String name) throws IOException, JroveException,
            ELException {
        if (name != null) {
            DefineHandler handler = this.handlers.get(name);
            if (handler != null) {
                handler.applyDefinition(ctx, parent);
                return true;
            } else {
                return false;
            }
        } else {
            this.nextHandler.apply(ctx, parent);
            return true;
        }
    }
}
